package com.example.music.activity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.adapter.AddSongsAdapter;
import com.example.music.model.Song;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public class AddSongsToPlaylistActivity extends AppCompatActivity implements AddSongsAdapter.OnSongSelectedListener {

    private RecyclerView recyclerView;
    private AddSongsAdapter adapter;
    private List<Song> songList;
    private TextView selectedCountTextView;
    private TextView emptyView;
    private int selectedCount = 0;
    private long playlistId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_songs);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 获取传递过来的歌单ID
        playlistId = getIntent().getLongExtra("playlist_id", -1);

        // 初始化歌曲列表数据
        songList = loadSongsFromDevice();
        Collections.sort(songList, new Comparator<Song>() {
            Collator collator = Collator.getInstance(Locale.CHINA);
            @Override
            public int compare(Song s1, Song s2) {
                return collator.compare(s1.getTitle(), s2.getTitle());
            }
        });

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddSongsAdapter(songList, this);
        recyclerView.setAdapter(adapter);

        selectedCountTextView = findViewById(R.id.selected_count);
        emptyView = findViewById(R.id.empty_view);

        SearchView searchView = findViewById(R.id.search_view);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.filter(newText);
                updateEmptyView();
                return true;
            }
        });

        updateEmptyView();
    }

    private List<Song> loadSongsFromDevice() {
        List<Song> songs = new ArrayList<>();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DURATION
        };

        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                songs.add(new Song(title, artist, album, path));
            }
            cursor.close();
        }
        return songs;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add_songs, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        } else if (item.getItemId() == R.id.action_confirm) {
            // 处理确认按钮点击事件
            handleConfirmClick();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void handleConfirmClick() {
        List<Song> selectedSongs = adapter.getSelectedSongs();
        Intent resultIntent = new Intent();
        resultIntent.putParcelableArrayListExtra("selected_songs", new ArrayList<>(selectedSongs));
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    @Override
    public void onSongSelected(Song song, boolean isSelected) {
        if (isSelected) {
            selectedCount++;
        } else {
            selectedCount--;
        }
        selectedCountTextView.setText("已选择: " + selectedCount + " 首");
        updateEmptyView();
    }

    private void updateEmptyView() {
        if (adapter.getItemCount() == 0) {
            emptyView.setVisibility(View.VISIBLE);
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }
}



